<template>
  <div class="creation">
    <view class="creation_content">
      <swiper :indicator-dots="autoplay" :autoplay="autoplay" interval="3000" circular="true"
        class="swiper creation_content_maximg" @change="onSwiperChange" :current="currentIndex">
        <swiper-item v-for="(item, index) in dataList" :key="index" class="creation_content_maximg">
          <image :src="item.thuImageUrl" @click="previewImage(index)" class="swiper-image creation_content_maximg"
            mode="aspectFill" />
          <text @click="getaddlist(true)" v-if="state == false" class="active">选择此模板</text>
          <text @click="getaddlist(false)" v-else>取消此模板</text>
          <view @click="getaddlist(true)" v-if="state == false"></view>
          <image @click="getaddlist(false)" v-else class="icon" src="/static/tabs/zhengque.png" mode="scaleToFill" />
        </swiper-item>
      </swiper>
      <view class="creation_content_text">滑动图片切换</view>
      <!-- <view class="creation_content_maximg">
        <image class="creation_content_maximg" :src="maximgs" mode="aspectFill" />
        <text @click="getaddlist(true)" v-if="state == false" class="active">选择此模板</text>
        <text @click="getaddlist(false)" v-else>取消此模板</text>
        <view @click="getaddlist(true)" v-if="state == false"></view>
        <image @click="getaddlist(false)" v-else class="icon" src="/static/tabs/zhengque.png" mode="scaleToFill" />
      </view> -->
      <view class="creation_content_model">
        <view class="creation_content_model_title">{{ TopicName == '' ? '最新热门' : TopicName }}</view>
        <view class="creation_content_model_list">
          <image :src="item.thuImageUrl" mode="aspectFill" v-for="(item, index) in dataList" :key="item.id"
            :class="{ active: item.id == activeid }" @click="getmaximg(item)" />
        </view>
      </view>
      <view class="creation_content_upload">
        <view class="creation_content_upload-left" @click="uplodimg" v-if="!ImageUrl">+</view>
        <view class="creation_content_upload-left" style="font-size: 22rpx;" @click="uplodimg" v-else>重新上传</view>
        <image class="uplodimgs" :src="ImageUrl" mode="aspectFill" v-if="ImageUrl" />
        <view class="creation_content_upload-right" :style="{ 'border-left': ImageUrl ? '2rpx solid #ccc' : '' }">
          <image :src="item.thuImageUrl" mode="aspectFill" v-for="item in modelimglist" :key="item.id"
            @click="getmaximg(item)" />
        </view>
      </view>
      <view class="creation_content_tishi">本人照片</view>
      <view class="creation_content_but" @click="funcreation">
        开始制作
      </view>
    </view>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue'
import { onLoad, onShow, onReady } from "@dcloudio/uni-app"
import { GetModeList, CreateQuest, UploadImagetep, WxUserLogin, GetUserInfo } from "@/api/user";
import { useUserStore } from '@/stores'
const userStore = useUserStore()
const TopicID = ref(0)
const TopicName = ref('') //搜索词条
const dataList: any = ref([])
const maximgs = ref('')
const activeid = ref('')
const state = ref(false)
const modelimglist = ref<any>([])
const ImageUrl = ref('')
const autoplay = ref(false)
const currentIndex = ref(0)
onLoad(async (options: any) => {
  autoplay.value = false
  TopicID.value = options.id
  TopicName.value = options.name
  activeid.value = options.activeid
  maximgs.value = options.img
  decryptPhoneNumber()
  getList()
})
// 模板列表
const getList = async () => {
  let data = {
    TopicID: TopicID.value,
  }
  let res: any = await GetModeList(data)
  if (res.code == 0) {
    currentIndex.value = res.data.findIndex(item => item.id == activeid.value);
    dataList.value = res.data.map((item: any) => (
      {
        ...item,
        state: false,
      }
    ))
    // maximgs.value = res.data[0].thuImageUrl
    // activeid.value = res.data[0].id
  }
}
// 监听轮播图切换事件
const onSwiperChange = (event) => {
  let currentIndex = event.detail.current;  // 获取当前显示的轮播项的索引
  activeid.value = dataList.value[currentIndex].id
  state.value = dataList.value[currentIndex].state
}
// 点击图片时触发预览
const previewImage = (index) => {
  let img = dataList.value[index].imageUrl
  console.log(img, 'aaaa');

  uni.previewImage({
    current: img, // 当前显示图片的链接
    urls: [
      img
      // 'https://via.placeholder.com/300', // 图片的 URL 列表
      // 'https://via.placeholder.com/350', // 可预览的其他图片
      // 'https://via.placeholder.com/400',
    ]
  });
}
const getmaximg = (item: any) => {
  maximgs.value = item.thuImageUrl
  activeid.value = item.id
  currentIndex.value = dataList.value.findIndex(item => item.id == activeid.value);
  state.value = item.state
}
const getaddlist = (flag) => {
  let element: any = dataList.value.find(item => item.id == activeid.value);
  if (element) {
    if (flag) {
      if (modelimglist.value.length == 10) {
        uni.showToast({
          title: '最多添加10张',
          icon: 'none',
        })
      } else {
        modelimglist.value.push(element)
        element.state = flag;
        state.value = flag
      }
    } else {
      modelimglist.value.splice(modelimglist.value.indexOf(element), 1);
      element.state = flag;
      state.value = flag
    }
  }
}
// 登陆
const decryptPhoneNumber = () => {
  let ids = wx.getStorageSync('scene');
  uni.login({
    provider: 'weixin',
    success: async function (loginRes) {
      if (!loginRes || !loginRes.code) {
        return
      }
      try {
        const res: any = await WxUserLogin({ code: loginRes.code, scene: ids })
        if (res.code == 0) {
          userStore.setUserInfo(res.data)
          getUserInfo(res.data)
          wx.removeStorageSync('scene');
        } else {
          console.error('User login failed:', res)
        }
      } catch (error) {
        console.error('Error during user login:', error)
      }
    },
    fail: function (err) {
      console.error('Login failed:', err)
    }
  })
}
// 获取用户信息
const getUserInfo = async (obj: any) => {
  const res: any = await GetUserInfo()
  const result = { ...res.data, ...obj }
  userStore.setUserInfo(result)
}
// 相册上传
const uplodimg = () => {
  uni.chooseImage({
    count: 1, //默认9
    sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
    sourceType: ['album', 'camera'], //从相册选择
    success: function (res) {
      uni.getImageInfo({
        src: res.tempFilePaths[0],
        success: (imageInfo) => {
          // console.log('图片宽度:', imageInfo.width);
          // console.log('图片高度:', imageInfo.height);
          if (imageInfo.width > 2048 || imageInfo.height > 2048) {
            let wed: any;
            let het: any;
            if (imageInfo.width > 2048) {
              wed = 2048
              het = 2048 / imageInfo.width * imageInfo.height
            } else {
              het = 2048
              wed = 2048 / imageInfo.height * imageInfo.width
            }

            uni.compressImage({
              src: res.tempFilePaths[0], // 图片路径
              quality: 80, // 压缩质量，范围0～100
              width: wed, // 缩放后的宽度，可以是像素值或百分比
              height: het, // 缩放后的高度
              success: (compressedRes) => {
                // console.log('压缩后的图片路径:', compressedRes);
                convertToBase64(compressedRes.tempFilePath)
              },
              fail: (err) => {
                console.log('压缩失败', err);
              }
            });

          } else {
            convertToBase64(res.tempFilePaths[0])
          }
        },
        fail: (err) => {
          console.log('获取图片信息失败', err);
        }
      })
    }
  });
}
function convertToBase64(filePath: any) {
  uni.showLoading({
    title: '上传中'
  });
  const fs = uni.getFileSystemManager(); // 获取文件系统管理器  
  fs.readFile({
    filePath: filePath, // 要读取的文件路径  
    encoding: 'base64', // 以Base64编码读取文件  
    success: async (result) => {
      const base64Data = result.data; // 获取Base64编码的字符串  
      // console.log('Base64编码的图片数据:', base64Data);
      let res: any = await UploadImagetep({
        img: base64Data
      })
      ImageUrl.value = res.data.imgurl
      uni.hideLoading();
      // console.log(res, 'akjsndiowsugdfuiwerhb');
    },
    fail: (err) => {
      console.error('读取文件失败:', err);
    }
  });
}
const funcreation = async () => {
  if (ImageUrl.value == '') {
    uni.showToast({
      title: '请上传完图片在创作～',
      duration: 2000,
      icon: 'none'
    })
    return
  }
  if (modelimglist.value.length == 0) {
    uni.showToast({
      title: '请选择喜欢的模型～',
      duration: 2000,
      icon: 'none'
    })
    return
  }
  let ids = modelimglist.value.map(item => item.id).join(',');
  let res = await CreateQuest({
    ImageUrl: ImageUrl.value,
    ModeID: ids
  })
  if (res.code == 0) {
    uni.showToast({
      title: '创建任务成功,即将跳转历史记录查询结果~',
      duration: 2000,
      icon: 'none'
    })
    setTimeout(() => {
      uni.switchTab({
        url: '/pages/history/index'
      })
    }, 2000)
  }
}
</script>

<style lang="scss" scoped>
page {
  background-color: #F7F7F7;
}

.creation {
  width: 100%;

  &_content {
    width: calc(100% - 64rpx);
    margin: 0 auto;

    &_maximg {
      width: 550rpx;
      height: 830rpx;
      border-radius: 16rpx;
      display: block;
      margin: auto;
      position: relative;

      text {
        // width: 100rpx;
        padding: 5rpx 20rpx;
        height: 50rpx;
        background-color: rgb(255, 255, 255, 0.6);
        position: absolute;
        bottom: 20rpx;
        left: 50%;
        transform: translateX(-50%);
        border-radius: 10rpx;
        text-align: center;
        line-height: 50rpx;
        font-size: 30rpx;
      }

      .active {
        background: linear-gradient(45deg, #fffacd, #ffdd99, #ffcce6);
      }

      view {
        width: 30rpx;
        height: 30rpx;
        border-radius: 50%;
        border: 1rpx solid #fff;
        position: absolute;
        top: 20rpx;
        right: 20rpx;
      }

      .icon {
        width: 32rpx;
        height: 32rpx;
        border-radius: 50%;
        position: absolute;
        top: 20rpx;
        right: 20rpx;
      }
    }

    &_text {
      width: 100%;
      text-align: center;
      font-size: 30rpx;
      margin-top: 5rpx;
      color: #222;
    }

    &_model {
      width: 100%;
      margin-top: 20rpx;

      &_title {
        font-size: 32rpx;
        color: #222;
      }

      &_list {
        margin-top: 20rpx;
        display: flex;
        width: 100%;
        // height: 150rpx;
        white-space: nowrap;
        /* 防止内容换行 */
        overflow-x: auto;
        overflow-y: hidden;
        /* 隐藏垂直滚动 */
        /* 可选 - 隐藏滚动条但保持滚动功能 (WebKit浏览器) */
        scrollbar-width: none;
        /* Firefox */
        -ms-overflow-style: none;

        /* IE/Edge */
        image {
          height: 150rpx;
          width: 90rpx;
          background-color: antiquewhite;
          margin-right: 20rpx;
          border-radius: 10rpx;
          flex-shrink: 0;
          border: 1rpx solid #fff;
        }

        .active {
          border: 1rpx solid yellow;
        }
      }
    }

    &_upload {
      display: flex;
      margin-top: 40rpx;

      &-left {
        width: 100rpx;
        height: 100rpx;
        border-radius: 50%;
        border: 2rpx solid #ccc;
        font-size: 80rpx;
        line-height: 95rpx;
        text-align: center;
        color: #666;
        flex-shrink: 0;
      }

      .uplodimgs {
        width: 100rpx;
        height: 100rpx;
        border-radius: 50%;
        border: 2rpx solid #ccc;
        margin-right: 15rpx;
        flex-shrink: 0;
        margin-left: 15rpx;
      }

      &-right {
        display: flex;
        padding-left: 20rpx;
        width: calc(100% - 100rpx - 20rpx);
        white-space: nowrap;
        /* 防止内容换行 */
        overflow-x: auto;
        overflow-y: hidden;
        /* 隐藏垂直滚动 */
        /* 可选 - 隐藏滚动条但保持滚动功能 (WebKit浏览器) */
        scrollbar-width: none;
        /* Firefox */
        -ms-overflow-style: none;
        /* IE/Edge */

        image {
          width: 100rpx;
          height: 100rpx;
          border-radius: 50%;
          border: 2rpx solid #ccc;
          margin-right: 15rpx;
          flex-shrink: 0;
        }
      }

      &-right::-webkit-scrollbar {
        display: none;
        /* Chrome/Safari/Opera */
      }
    }

    &_tishi {
      font-size: 28rpx;
      color: #666;
    }

    &_but {
      width: calc(100% - 64rpx);
      height: 90rpx;
      background: linear-gradient(45deg, #fffacd, #ffdd99, #ffcce6);
      border-radius: 45rpx;
      line-height: 90rpx;
      font-size: 36rpx;
      text-align: center;
      font-weight: 600;
      position: fixed;
      bottom: 70rpx;
    }
  }
}
</style>